#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_timer.h"
#include "esp_log.h"
#include "esp_sleep.h"
#include "sdkconfig.h"
#include "esp_wifi.h"
#include "oled_driver.h"
#include "countdown_timer.h"
#include "wifistation.h"

#define TAG "Timer"
#define TOTAL_COUNTDOWN (9*60*60)

static esp_timer_handle_t periodic_timer;
static uint32_t remainSecond = 0;
static uint32_t alreadyPass = 0;
static uint8_t timer_start_flag = 0;

extern QueueHandle_t disply_queue;
extern uint8_t bluetooth_flag;

static void periodic_timer_callback(void* arg)
{
    uint8_t display_type = WORK_NONE;
    // int32_t time_since_boot = esp_timer_get_time();
    // ESP_LOGI(TAG, "Periodic timer called, time since boot: %lld us", time_since_boot);
    alreadyPass++;

    if(alreadyPass >= TOTAL_COUNTDOWN)
    {
        alreadyPass = 0;
        stopCountDownTimer();
        display_type = WORK_OFF;
    }
    else
    {
        display_type = WORK_COUNT_DOWN;
    }
    xQueueSend(disply_queue, &display_type, NULL);
}

uint32_t getRemainTime(void)
{
    return (TOTAL_COUNTDOWN - alreadyPass);//second
}

void startCountDownTimer(void)
{
    if(0 == timer_start_flag)
    {
        timer_start_flag = 1;
        ESP_ERROR_CHECK(esp_timer_start_periodic(periodic_timer, 1000*1000));
        ESP_LOGI(TAG, "Start Periodic timer");
    }
}

void stopCountDownTimer(void)
{
    if(1 == timer_start_flag)
    {
        timer_start_flag = 0;
        ESP_ERROR_CHECK(esp_timer_stop(periodic_timer));
        ESP_LOGI(TAG, "Stop Periodic timer");
    }
}

void countDownTimerInit(void)
{
    const esp_timer_create_args_t periodic_timer_args = {
        .callback = &periodic_timer_callback,
        /* name is optional, but may help identify the timer when debugging */
        .name = "periodic"
    };

    ESP_ERROR_CHECK(esp_timer_create(&periodic_timer_args, &periodic_timer));
    ESP_LOGI(TAG, "Init Periodic timer");
}

void countDownTimerUnInit(void)
{
    ESP_ERROR_CHECK(esp_timer_stop(periodic_timer));
    ESP_ERROR_CHECK(esp_timer_delete(periodic_timer));
    ESP_LOGI(TAG, "UnInit Periodic timer");
}

void deal_data_time(void)
{
    uint8_t display_type = WORK_NONE;
    char strftime_buf[32];//"%H:%M:%S"
    uint32_t temp = 0;
    static uint32_t last_time_us = 0;

    if(IP_EVENT_STA_GOT_IP == get_wifi_status())
    {
        temp = esp_timer_get_time();
        if((temp - last_time_us) > 60 * 1000000)//1 min
        {
            getCurrentTime(strftime_buf);
            if(strcmp("23:58:59", strftime_buf) < 0)//will tomorrow
            {
                bluetooth_flag = 0;
                display_type = WORK_WAITING;
                xQueueSend(disply_queue, &display_type, NULL);
            }
        }
    }
}
